package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.CheckInApplyDto;
import com.zzyl.serve.dto.CheckInConfigDto;
import com.zzyl.serve.dto.CheckInElderDto;
import com.zzyl.serve.dto.ElderFamilyDto;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.service.ICheckInConfigService;
import com.zzyl.serve.util.CodeGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author liusm
 * @date 2025-08-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }


    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.如果老人已经入住(老人身份证号已存在,且状态为1),则抛异常
        LambdaQueryWrapper<Elder> wrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        Elder elderDb = elderMapper.selectOne(wrapper);
       if (elderDb!=null && Objects.equals(elderDb.getStatus(),1)){
            throw new BaseException("老人已入住");
        };
        //2.更新床位状态为"已入住"(如果床位是未入住时才允许入住)
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        if (Objects.equals(bed.getBedStatus(),1)){
            throw new BaseException("床位已入住");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);


        //3.保存老人信息
        //将 dto中老人的信息封装成Elder对象
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elder= new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        List<ElderFamilyDto> familyDtoList = dto.getElderFamilyDtoList();
        //将familyDtoList转换成json格式的字符串
        elder.setRemark(JSONUtil.toJsonStr(familyDtoList));
        if (elderDb==null){
            //如果刚才从数据库中查询的老人为null: 要新增老人信息
            elderMapper.insert(elder);
        }else{
            //要更新老人信息
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }

        //4.新增入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(dto.getCheckInElderDto().getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        save(checkIn);
        //5.新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
        //6.新增签约信息
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractName(CodeGenerator.generateContractNumber());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        //如果当前时间不早于合同开始时间,且不晚于合同结束时间,说明在合同有效期内
        LocalDateTime now = LocalDateTime.now();
        if (!now.isAfter(contract.getStartDate()) && !now.isBefore(contract.getEndDate())){
            contractMapper.insert(contract);
        }
    }
}
